import API from "@/server";
import CONFIG from "@/assets/raw/config.js";
// 封装网络请求
export default async (url = "", data = {}, type = "GET", headers = null) => {
    const userInfo = API.getUserInfo();
    // 基础路径配置
    // const baseUrl = '';
    // 请求方式小写转成大写
    type = type.toUpperCase();
    let dataStr = "";
    if (data) {
        // 数据拼接字符串
        Object.keys(data).forEach((key) => {
            dataStr += key + "=" + data[key] + "&";
        });
        dataStr += "t=" + new Date().getTime();
    }
    if (type == "GET") {
        url += `?${dataStr}`;
    }
    // const timeout = Math.abs(CONFIG.DEFAULT_TIMEOUT || 10) * 1e3;
    let requestConfig = {
        method: type,
        // 请求头使用入参或者默认
        headers: {
            // timeout: timeout,
            Accept: "application/json",
            "Content-Type": "application/json",
            serviceChannelId: userInfo.serviceChannelId || "",
            ...headers,
        },
    };
    console.log("requestConfig:requestConfig", JSON.stringify(requestConfig));
    if (type == "POST" || type == "DELETE") {
        let body;
        // 根据POST的Content-Type对应两种参数方法
        if (requestConfig.headers["Content-Type"] === "application/json") {
            body = JSON.stringify(data);
        } else {
            body = dataStr;
        }
        // 此处不理解为何要用Object.defineProperty
        Object.defineProperty(requestConfig, "body", {
            value: body,
        });
        console.log("Query post data:" + JSON.stringify(body));
    }
    console.log("requestConfig:url", url);
    const timeoutPromise = (timeout) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                console.log("H5 timeout back");
                resolve({
                    status: "timeout",
                    statusText: "request frontend timeout",
                });
            }, timeout);
        });
    };
    try {
        if (data.timeout) {
            console.log("use data.timeout 001");
            const response = await Promise.race([
                timeoutPromise(data.timeout),
                fetch(url, requestConfig),
            ]);
            if (response.status === "timeout") {
                console.log("use data.timeout 002");
                return response;
            }
            const responseJson = await response.json();
            console.log("use data.timeout 003");
            return responseJson;
        }
        const response = await fetch(url, requestConfig);
        // console.log("response:", JSON.stringify(response));
        const responseJson = response.body ? await response.json() : response;
        // console.log('response:json', responseJson);
        return responseJson;
    } catch (error) {
        console.log("responseError", error);
        return { status: "error", statusText: error };
    }
};
